#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dwgobjectitem.h"
#include <QShortcut>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : SARibbonMainWindow(parent), mMenuApplicationBtn(nullptr), ui(new Ui::MainWindow)
{
    setWindowIcon(QIcon(":/icon/icons/png/32x32/logo.png"));    // logo

    ui->setupUi(this);

    setWindowTitle(("Drawing1.dwg - YunaCAD"));    // 标题栏

    int w,h;
    w = ui->graphicsView->width()*10; // 定义绘图区域的长
    h = ui->graphicsView->height()*10; // 定义绘图区域的宽
    m_scene = new QGraphicsScene(0,0,w*1.8,h*3.2); // 场景全局只有一个，在构造函数中初始化它，

    // 可以依据需求设置场景大小与视图大小
    ui->graphicsView->setScene(m_scene); // 把场景与视图连接起来

    //ui->graphicsView->setBackgroundBrush(Qt::gray); // 设置背景为灰色

    setMinimumWidth(500);   //窗口最小宽度尺寸
    showMaximized();    // 默认最大化窗口启动

    // 设置和修改applicationButton
    createRibbonApplicationButton();

    SARibbonBar* ribbon = ribbonBar();
    ribbon->setContentsMargins(5, 0, 5, 0); // 通过setContentsMargins设置ribbon四周的间距
    this->ribbonBar()->showMinimumModeButton(); // 显示ribbon最小化按钮

    // 添加绘图标签页
    SARibbonCategory* categoryDraw = ribbon->addCategoryPage(tr("&Draw"));
    categoryDraw->setObjectName(("categoryDraw"));
    createCategoryDraw(categoryDraw);

    // 添加修改标签页
    SARibbonCategory* categoryModify = ribbon->addCategoryPage(tr("&Modify"));
    categoryModify->setObjectName(("categoryModify"));
    createCategoryModify(categoryModify);

    // 在系统窗口最小化最大化关闭按钮旁边添加按钮
    createWindowButtonGroupBar();

    // 在系统窗口图标旁添加按钮
    createQuickAccessBar();
}

MainWindow::~MainWindow()
{
    delete ui;
    m_scene->clear(); // 清空场景中的图形项
    delete m_scene; // 释放场景变量内存
}

void MainWindow::on_actionExit_triggered()
{
    this->close();
}

void MainWindow::on_actionPoint_triggered()
{
    ui->graphicsView->mCurDrawType = DPoint;
    ui->graphicsView->mCurModifyType = MNone;
    ui->graphicsView->setCursor(Qt::CrossCursor);
}

void MainWindow::on_actionLine_triggered()
{
    ui->graphicsView->isFirst = true;
    ui->graphicsView->mCurDrawType = DLine;
    ui->graphicsView->mCurModifyType = MNone;
    ui->graphicsView->setCursor(Qt::CrossCursor);

    /* 下面的代码是为了遍历场景中的所有图元，并把它们的可选择属性都设计为 false，也就是不可选择
    QList<QGraphicsItem *> items = m_scene->items();
    if(!items.isEmpty())
    {
        foreach (auto item, items) {
            // 设置所有图元为可选择
            item->setFlag(QGraphicsItem::ItemIsSelectable, false);
        }
    }*/
}

void MainWindow::on_actionPolyLine_triggered()
{
    ui->graphicsView->isFirst = true;
    ui->graphicsView->mCurDrawType = DPolyLine;
    ui->graphicsView->mCurModifyType = MNone;
    ui->graphicsView->setCursor(Qt::CrossCursor);
}

void MainWindow::on_actionCircle_triggered()
{
    ui->graphicsView->isFirst = true;
    ui->graphicsView->mCurDrawType = DCircle;
    ui->graphicsView->mCurModifyType = MNone;
    ui->graphicsView->setCursor(Qt::CrossCursor);
}

void MainWindow::on_actionEllipse_triggered()
{
    ui->graphicsView->isFirst = true;
    ui->graphicsView->isSecond = true;
    ui->graphicsView->mCurDrawType = DEllipse;
    ui->graphicsView->mCurModifyType = MNone;
    ui->graphicsView->setCursor(Qt::CrossCursor);
}

void MainWindow::on_actionRect_triggered()
{
    ui->graphicsView->isFirst = true;
    ui->graphicsView->mCurDrawType = DRectangle;
    ui->graphicsView->mCurModifyType = MNone;
    ui->graphicsView->setCursor(Qt::CrossCursor);
}

void MainWindow::on_actionSelect_triggered()
{
    ui->graphicsView->mCurDrawType = DNone;
    ui->graphicsView->mCurModifyType = MSelect;

    QList<QGraphicsItem *> items = m_scene->items();
    if(!items.isEmpty())
    {
        foreach (auto item, items) {
            // 设置所有图元为可选择
            item->setFlags(QGraphicsItem::ItemIsSelectable);
        }
    }
}

void MainWindow::on_actionMove_triggered()
{
    ui->graphicsView->mCurDrawType = DNone;
    ui->graphicsView->mCurModifyType = MMove;
    ui->graphicsView->setDragMode(QGraphicsView::RubberBandDrag);               // 打开视图的框选模式

    QList<QGraphicsItem *> items = m_scene->items();
    if(!items.isEmpty())
    {
        foreach (auto item, items) {
            // 设置所有图元为可选择和可移动属性
            item->setFlags(QGraphicsItem::ItemIsSelectable|QGraphicsItem::ItemIsMovable);
        }
    }
}

void MainWindow::on_actionDelete_triggered()
{
    ui->graphicsView->mCurDrawType = DNone;
    ui->graphicsView->mCurModifyType = MDelete;
    m_scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    QList<QGraphicsItem *> deleteitems = m_scene->selectedItems();
    for(auto i :deleteitems)
    {
        m_scene->removeItem(i);
        delete i;
    }
    m_scene->setItemIndexMethod(QGraphicsScene::BspTreeIndex);
}

void MainWindow::onActionHelpTriggered()
{
    QMessageBox::information(this,
                             tr("YunaCAD - infomation"),
                             tr("\n ==============="
                                "\n YunaCAD version:%1"
                                "\n Author:Yunamie"
                                "\n Email:yunamie@126.com"
                                "\n ===============")
                                 .arg(SARibbonBar::versionString()));
}

void MainWindow::on_ActionColor_triggered(const QColor& c)
{
    ui->graphicsView->myCurColor = c.name();
}

void MainWindow::on_ActionPenStyle_triggered(int index)
{
    switch(index)
    {
    case 0:
        ui->graphicsView->myCurPenStyle = Qt::SolidLine;
        break;
    case 1:
        ui->graphicsView->myCurPenStyle = Qt::DashLine;
            break;
    case 2:
        ui->graphicsView->myCurPenStyle = Qt::DotLine;
            break;
    case 3:
        ui->graphicsView->myCurPenStyle = Qt::DashDotLine;
            break;
    case 4:
        ui->graphicsView->myCurPenStyle = Qt::DashDotDotLine;
            break;
    case 5:
        ui->graphicsView->myCurPenStyle = Qt::CustomDashLine;
        break;
    default:
        break;
    }
}

void MainWindow::closeEvent(QCloseEvent* e)
{
    auto res = QMessageBox::question(this, tr("YunaCAD"), tr("Confirm whether to exit"));
    if (res == QMessageBox::Yes) {
        e->accept();
    } else {
        e->ignore();
    }
}

void MainWindow::createRibbonApplicationButton()
{
    SARibbonBar* ribbon = ribbonBar();
    if (!ribbon) {
        return;
    }
    QAbstractButton* btn = ribbon->applicationButton();
    if (!btn) {
        // SARibbonBar默认就会创建一个SARibbonApplicationButton，因此，在正常情况下，这个位置不会进入
        btn = new SARibbonApplicationButton(this);
        ribbon->setApplicationButton(btn);
    }
    ribbon->applicationButton()->setText(("  &File  "));  // 文字两边留有间距，好看一点
    // SARibbonMenu和QMenu的操作是一样的
    if (!mMenuApplicationBtn) {
        mMenuApplicationBtn = new SARibbonMenu(this);
        mMenuApplicationBtn->addAction(createAction("New", ":/icon/icons/png/32x32/New file.png"));
        mMenuApplicationBtn->addAction(createAction("Open", ":/icon/icons/png/32x32/Open.png"));
        mMenuApplicationBtn->addAction(createAction("Save", ":/icon/icons/png/32x32/Save.png"));
        mMenuApplicationBtn->addAction(createAction("Save as", ":/icon/icons/png/32x32/Save as.png"));
        QAction* actExit = createAction(tr("Exit"), ":/icon/icons/png/32x32/Exit.png");
        // 设置快捷键
        QShortcut* shortCut = new QShortcut(QKeySequence(QLatin1String("Ctrl+Shift+S")), this);
        connect(shortCut, &QShortcut::activated, this, [ actExit ]() { actExit->trigger(); });

        //connect(actExit, &QAction::triggered, this, [ this ]() { this->close(); });
        connect(actExit, &QAction::triggered, this, &::MainWindow::on_actionExit_triggered);
        mMenuApplicationBtn->addAction(actExit);
    }
    SARibbonApplicationButton* appBtn = qobject_cast< SARibbonApplicationButton* >(btn);
    if (!appBtn) {
        return;
    }
    appBtn->setMenu(mMenuApplicationBtn);
}

void MainWindow::createCategoryDraw(SARibbonCategory* page)
{
    // 使用addPannel函数来创建SARibbonPannel
    SARibbonPannel* pannelDraw = page->addPannel(("绘图"));

    QAction* actLine = createAction(tr("Line"), ":/icon/icons/png/32x32/Line.png");
    connect(actLine, &QAction::triggered, this, &::MainWindow::on_actionLine_triggered);
    pannelDraw->addLargeAction(actLine);

    //pannelDraw->addAction(tr("PolyLine"), QIcon(":/icon/icons/png/32x32/Angle.png")
    //                      , QToolButton::InstantPopup, SARibbonPannelItem::Small);
    QAction* actPolyLine = createAction(tr("PolyLine"), ":/icon/icons/png/32x32/Angle.png");
    connect(actPolyLine, &QAction::triggered, this, &::MainWindow::on_actionPolyLine_triggered);
    pannelDraw->addLargeAction(actPolyLine);

    QAction* actCircle = createAction(tr("Circle"), ":/icon/icons/png/32x32/Circle.png");
    connect(actCircle, &QAction::triggered, this, &::MainWindow::on_actionCircle_triggered);
    pannelDraw->addLargeAction(actCircle);

    QAction* actRect = createAction(tr("Rectangle"), ":/icon/icons/png/32x32/Restangle.png", false);
    connect(actRect, &QAction::triggered, this, &::MainWindow::on_actionRect_triggered);
    pannelDraw->addSmallAction(actRect);

    QAction* actEllipse = createAction(tr("Ellipse"), ":/icon/icons/png/32x32/Ellipse.png", false);
    connect(actEllipse, &QAction::triggered, this, &::MainWindow::on_actionEllipse_triggered);
    pannelDraw->addSmallAction(actEllipse);

    QAction* actPoint = createAction(tr("Point"), ":/icon/icons/png/32x32/Target1.png", false);
    connect(actPoint, &QAction::triggered, this, &::MainWindow::on_actionPoint_triggered);
    pannelDraw->addSmallAction(actPoint);

    pannelDraw->addSeparator();

    SARibbonPannel* pannelProperty = page->addPannel(("特性"));

    // 画笔颜色选择按钮
    auto fpCreateBtn = [ this, pannelProperty ](const QColor& defaultColor = Qt::black) -> SARibbonColorToolButton* {
        SARibbonColorToolButton* colorButton = new SARibbonColorToolButton(pannelProperty);
        colorButton->setColor(defaultColor);
        colorButton->setupStandardColorMenu();
        connect(colorButton, &SARibbonColorToolButton::colorClicked, this, &MainWindow::on_ActionColor_triggered);
        return colorButton;
    };
    SARibbonColorToolButton* colorButton = fpCreateBtn();
    // No Icon have text
    colorButton = fpCreateBtn(Qt::black);
    colorButton->setColorStyle(SARibbonColorToolButton::ColorFillToIcon);
    colorButton->setObjectName("ColorFillToIcon-NoIconHaveText");
    colorButton->setText(QString("Color"));
    pannelProperty->addSmallWidget(colorButton);

    // 线宽LineEdit
    mLineWidthEditor = new SARibbonLineEdit(this);
    //mLineWidthEditor->setFixedWidth(80);
    mLineWidthEditor->setPlaceholderText("LineWidth");
    pannelProperty->addSmallWidget(mLineWidthEditor);
    connect(mLineWidthEditor, &QLineEdit::editingFinished, this, [ this ]() {
        ui->graphicsView->myCurLineWidth = this->mLineWidthEditor->text().toInt();
    });

    SARibbonComboBox* myCurPenStyle = new SARibbonComboBox();
    myCurPenStyle->setWindowTitle(tr("PenStyle"));
    myCurPenStyle->setObjectName("PenStyle");
    myCurPenStyle->addItem("SolidLine");
    myCurPenStyle->addItem("DashLine");
    myCurPenStyle->addItem("DotLine");
    myCurPenStyle->addItem("DashDotLine");
    myCurPenStyle->addItem("DashDotDotLine");
    myCurPenStyle->addItem("CustomDashLine");
    connect(myCurPenStyle, QOverload< int >::of(&SARibbonComboBox::currentIndexChanged), this, &MainWindow::on_ActionPenStyle_triggered);
    pannelProperty->addSmallWidget(myCurPenStyle);
}

void MainWindow::createCategoryModify(SARibbonCategory* page)
{
    // 使用addPannel函数来创建SARibbonPannel
    SARibbonPannel* pannelModify = page->addPannel(("修改"));

    QAction* actSelect = createAction(tr("Select"), ":/icon/icons/png/32x32/Selection.png");
    connect(actSelect, &QAction::triggered, this, &::MainWindow::on_actionSelect_triggered);
    pannelModify->addSmallAction(actSelect);

    QAction* actMove = createAction(tr("Move"), ":/icon/icons/png/32x32/Move.png");
    connect(actMove, &QAction::triggered, this, &::MainWindow::on_actionMove_triggered);
    pannelModify->addSmallAction(actMove);

    QAction* actDelete = createAction(tr("Delete"), ":/icon/icons/png/32x32/Erase.png");
    connect(actDelete, &QAction::triggered, this, &::MainWindow::on_actionDelete_triggered);
    pannelModify->addSmallAction(actDelete);
}

void MainWindow::createWindowButtonGroupBar()
{   
    SARibbonSystemButtonBar* wbar = windowButtonBar();
    if (!wbar) {
        return;
    }

    SARibbonLineEdit* mSearchEditor = new SARibbonLineEdit(this);
    mSearchEditor->setFixedWidth(100);
    mSearchEditor->setPlaceholderText("Search");
    wbar->addWidget(mSearchEditor);
    //connect(mSearchEditor, &QLineEdit::editingFinished, this, );

    QAction* actionHelp = createAction(tr("help"), ":/icon/icons/png/32x32/Help.png");
    connect(actionHelp, &QAction::triggered, this, &MainWindow::onActionHelpTriggered);
    wbar->addAction(actionHelp);
}

void MainWindow::createQuickAccessBar()
{
    SARibbonQuickAccessBar* quickAccessBar = ribbonBar()->quickAccessBar();

    quickAccessBar->addAction(createAction("New", ":/icon/icons/png/32x32/New file.png"));
    quickAccessBar->addAction(createAction("Open", ":/icon/icons/png/32x32/Open.png"));
    quickAccessBar->addAction(createAction("Save", ":/icon/icons/png/32x32/Save.png", "save-quickbar"));
    quickAccessBar->addAction(createAction("Save as", ":/icon/icons/png/32x32/Save as.png"));
    quickAccessBar->addSeparator();

    QAction* actionUndo = createAction("undo", ":/icon/icons/png/32x32/Undo.png");
    actionUndo->setShortcut(QKeySequence("Ctrl+Shift+z"));
    actionUndo->setShortcutContext(Qt::ApplicationShortcut);
    quickAccessBar->addAction(actionUndo);

    QAction* actionRedo = createAction("redo", ":/icon/icons/png/32x32/Redo.png");
    actionRedo->setShortcut(QKeySequence("Ctrl+z"));
    actionRedo->setShortcutContext(Qt::ApplicationShortcut);
    quickAccessBar->addAction(actionRedo);

    //connect(actionUndo, &QAction::triggered, this, });
    //connect(actionRedo, &QAction::triggered, this, });
}

void MainWindow::createOtherActions() {}

void MainWindow::createActionsManager()
{
    // 添加其他的action，这些action并不在ribbon管理范围，主要用于SARibbonCustomizeWidget自定义用
    createOtherActions();
    mTagForActionText = SARibbonActionsManager::UserDefineActionTag + 1;
    mTagForActionIcon = SARibbonActionsManager::UserDefineActionTag + 2;

    mActionsManager = new SARibbonActionsManager(ribbonBar());  // 申明过程已经自动注册所有action
}

QAction* MainWindow::createAction(const QString& text, const QString& iconurl,const QString& objName, const bool& textOn)
{
    QAction* act = new QAction(this);
    if (textOn)
        act->setText(text);
    act->setIcon(QIcon(iconurl));
    act->setObjectName(objName);
    return act;
}

QAction* MainWindow::createAction(const QString& text, const QString& iconurl, const bool& textOn)
{
    QAction* act = new QAction(this);
    if (textOn)
        act->setText(text);
    act->setIcon(QIcon(iconurl));
    act->setObjectName(text);
    return act;
}
